package com.devbobcorn.nekoration.blocks.entities;

import javax.annotation.Nullable;

import com.devbobcorn.nekoration.utils.TagTypes;

import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.nbt.NBTUtil;
import net.minecraft.network.play.server.SUpdateTileEntityPacket;
import net.minecraft.tileentity.TileEntity;

public class CustomBlockEntity extends TileEntity {
    public Byte dir = 0;
    public int[] offset = { 0, 0, 0 };
    public Boolean retint = false, showHint = false;
    public int[] color = { 255, 255, 255 }; // RGB Color...

    public static BlockState defaultState = Blocks.AIR.defaultBlockState();
    public BlockState displayState = Blocks.AIR.defaultBlockState();

    public CustomBlockEntity() {
        super(ModTileEntityType.CUSTOM_TYPE.get());
    }
    
    @Override
    public CompoundNBT save(CompoundNBT tag) {
        super.save(tag); // The super call is required to save the tile's location
        tag.putByte("Dir", dir);
        tag.putIntArray("Offset", offset);
        tag.putByte("StateFlag", GetStateFlag());
        tag.putIntArray("Color", color);
        tag.put("Display", NBTUtil.writeBlockState(displayState));
        return tag;
    }

    // This is where you load the data that you saved in writeToNBT
    @Override
    public void load(BlockState state, CompoundNBT tag) {
        super.load(state, tag); // The super call is required to load the tile's location

        if (tag.contains("Dir", TagTypes.BYTE_NBT_ID)) {
            dir = tag.getByte("Dir");
        }
        if (tag.contains("Offset", TagTypes.INT_ARRAY_NBT_ID)) {
            offset = tag.getIntArray("Offset");
        }
        if (tag.contains("StateFlag", TagTypes.BYTE_NBT_ID)) {
            SetStateFlag(tag.getByte("StateFlag"));
        }
        if (tag.contains("Color", TagTypes.INT_ARRAY_NBT_ID)) {
            color = tag.getIntArray("Color");
        }
        if (tag.contains("Display", TagTypes.COMPOUND_NBT_ID)) {
            CompoundNBT dat = tag.getCompound("Display");
            displayState = NBTUtil.readBlockState(dat);
        }
    }

    private byte GetStateFlag() {
        int retintFlag = retint ? 1 : 0;
        int showHintFlag = showHint ? 2 : 0;
        return (byte)(retintFlag | showHintFlag);
    }

    public void SetStateFlag(Byte flag) {
        retint = (flag & 1) > 0;
        showHint = (flag & 2) > 0;
    }

    @Override
    @Nullable
    public SUpdateTileEntityPacket getUpdatePacket() {
        return new SUpdateTileEntityPacket(this.worldPosition, 2077, this.getUpdateTag());
    }

    public CompoundNBT getUpdateTag() {
        CompoundNBT tag = new CompoundNBT();
        this.save(tag);
        return tag;
    }

}